package com.geeke.sys.service;

import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import com.geeke.common.service.CrudService;
import com.geeke.common.data.PageRequest;
import com.geeke.common.data.Parameter;
import com.geeke.config.exception.CommonJsonException;
import com.geeke.sys.dao.SecurityDao;
import com.geeke.sys.entity.Security;
import com.geeke.sys.vo.SecurityVo;
import com.geeke.utils.ResultUtil;
import com.geeke.utils.constants.ErrorEnum;
import com.google.common.collect.Lists;

/**
 * 安全配置表 Service
 * @author
 * @version
 */
@Service("securityService")
@Transactional(readOnly = true)
public class SecurityService extends CrudService<SecurityDao, Security> {

    @Autowired
    private UserService userService;
    @Override
    public Security get(String id) {
        Security security = super.get(id);
        return security;
    }

    @Transactional(readOnly = false)
    @Override
    public Security save(Security security) {
        // 系统只能有一条安全配置记录，检查是否已存在
        if (StringUtils.isBlank(security.getId())) {
            List<Parameter> params = Lists.newArrayList();
            params.add(new Parameter("security.del_flag", "=", security.getDelFlag()));
            
            if (this.dao.count(new PageRequest(params)) > 0) {
                throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在安全配置，请勿重复创建"));
            }
        }
        
        Security securityTemp = super.save(security);
        return securityTemp;
    }

    @Override
    @Transactional(readOnly = false)
    public int delete(Security security) {
        int rows = super.delete(security);
        return rows;
    }
	
    @Transactional(readOnly = false)
    @CacheEvict(cacheNames = "security:config", allEntries = true)
    public boolean init(SecurityVo securityVo) {
        Security security = securityVo.getSecurity();

        Security securityDb = get(security.getId());
        // 已配置状态
        if(!"0".equals(securityDb.getConfigFlag())) {
            return false;
        }

        userService.changeLoginPassword("1000", securityVo.getPassWords()[0]);
        userService.changeLoginPassword("1001", securityVo.getPassWords()[1]);

        security.setConfigFlag("1");
        this.save(security);

        return true;
    }

    // 根据需求实现的其他方法
} 